
import {ChangeDetectorRef, Component} from "@angular/core";
import {NavController, NavParams, AlertController, ToastController, ActionSheetController} from "ionic-angular";
import {HttpService} from "../../providers/http.service";
import {CommonFunc} from "../../providers/commonFunc";
import { Storage } from "@ionic/storage";
import {CheckElevatorList} from "./check-elevator-list/check-elevator-list";
import {CheckElevatorScan} from "./check-elevator-scan/check-elevator-scan";
import {Camera,CameraOptions} from "@ionic-native/camera";
import {FileTransfer, FileTransferObject, FileUploadOptions} from "@ionic-native/file-transfer";
import {appConfig} from "../../providers/config";
import {PhotoViewer} from "@ionic-native/photo-viewer";

/**
 * 多台电梯检查
 */
@Component({
  templateUrl: "checkElevator.html"
})
export class CheckElevator {
    type = null;
    checkNameUrl: any = null;
    checkerId: any = null;
    checkerName: any = null;

    // 检查项集合
    public itemlist:any=[];
    // 计划Id
    public planId:any;
    // 电梯设备Id
    public elevatorId:any;
    // 多台电梯的集合
    public moreElevator:any=[];
    // 数组Id
    public num:number=0;

    public objData:any=[];
    // 实施对象
    public implementObject:any;
    // 负责人
    public headMan:any;
    // 检查人
    public checkMan:any;
    // userId
    public userId:any;

    public listMenu:any=[];

    public implementObjectId:any;
    // 定义电梯详细
    public elevatorIdInfo:any=[];
    // 定义电梯设备编号
    public elevatorNum:any;
    // 定义拍照照片
    public elevatorPicUrl:any;
    private appConfig: any;

    // 定义检查结果评价
    public resultEvaluate:any;

    // 定义意见
    public opinion:any;

    /*// 定义签字
    public signPhoto:any;*/


    constructor(
        public navParams: NavParams,
        private commonFunc: CommonFunc,
        private httpService: HttpService,
        private storage: Storage,
        private camera: Camera,
        private transfer: FileTransfer,
        private navCtrl: NavController,
        public alertCtrl: AlertController,
        public cd: ChangeDetectorRef,
        private photoViewer: PhotoViewer,
        private ActionSheet: ActionSheetController,
        private toast: ToastController
    ) {
        this.appConfig = appConfig;
        this.storage.get("user").then(data => {
            this.checkerId = data.id;
            this.checkerName = data.userName;
        });
    }
    ionViewWillEnter() {

        this.moreElevator=[];
        // 获取计划Id
        this.planId = this.navParams.get("planId");
        // 获取检查项
        this.checkItem();
        // 获取电梯设备Id
        this.elevatorId =this.navParams.get("elevatorId");

        console.log(this.elevatorId);
        // 获取实施对象Id
        this.implementObjectId = this.navParams.get("implementObjectId");
        // 获取数据判断类型
        let scanType = this.navParams.get("scanType");
        /*假数据列表*/
        /*scanType = '1';
        this.elevatorId = "2138";*/

        if(scanType !=undefined && scanType !=null && scanType=='1'){
            this.findElevatorInfo(this.elevatorId,this.implementObjectId);
        }

    }

    // 通过当前用户查询未检查记录以及检查项
    checkItem(){
       this.httpService.findCheckItemApp({"planId":this.planId}).subscribe(data => {

           if (data.status != 200) {
                let toast = this.commonFunc.showInsideErrorToast(data);
                toast.present();
                return;
            }
            this.itemlist = data.data;
        });

    }
    // 获取电梯信息
    findElevatorInfo(elevatorId,mantanceUserId){
        if(elevatorId == undefined || elevatorId ==null){
            let tt = this.toast.create({
                message: "请先扫描您要工作的电梯！",
                duration: 1000,
                position: "top"
            });
            tt.present();
            return false;
        }

        if(mantanceUserId ==undefined || mantanceUserId==null){
            let tt = this.toast.create({
                message: "您已经离线，请重新登录！",
                duration: 6000,
                position: "top"
            });
            tt.present();
            return false;
        }
        this.httpService.findElevatorInfo({"elevatorId":elevatorId,"mantanceUserId":mantanceUserId}).subscribe(data => {

            if (data.status != 200) {
                let toast = this.commonFunc.showInsideErrorToast(data);
                toast.present();
                return;
            }
            console.log(data);
            if(data.data.length==0){
                let tt = this.toast.create({
                    message: "此电梯不是实施对象维保的电梯，请重新扫描！",
                    duration: 4000,
                    position: "top"
                });
                tt.present();
                return false;
            }else {
                this.elevatorIdInfo = data.data;
                this.elevatorNum = this.elevatorIdInfo[0].elevatorNum;
            }
        });


    }
    // 开启扫描
    scanner(){
        // 跳转到扫描界面
        let workType='1'
        this.navCtrl.push(CheckElevatorScan,{"workType":workType,"implementObjectId":this.implementObjectId,"planId":this.planId});
    }

    // 完成
    presentAlert(){
        console.log("coming.....");
        console.log(this.resultEvaluate);
        console.log(this.opinion);


        if(this.elevatorId ==null || this.elevatorId==undefined || this.elevatorId==""){
            let tt = this.toast.create({
                message: "请先扫描电梯，进行检查！",
                duration: 4000,
                position: "top"
            });
            tt.present();
            return false;
        }

        if(this.elevatorIdInfo ==null || this.elevatorIdInfo==undefined || this.elevatorIdInfo.length==0 ){
            let tt = this.toast.create({
                message: "请先扫描电梯，进行检查!",
                duration: 4000,
                position: "top"
            });
            tt.present();
            return false;
        }

        if(this.itemlist !=null && this.itemlist.length>0 ){
            console.log("111111");
            for(var i=0;i<this.itemlist.length;i++){
                let item= this.itemlist[i];
                if(item.isChecked =='1'){
                    if(item.remarkes==undefined || item.result.picUrl.length==0){
                        let tt = this.toast.create({
                            message: "您已经选择了否,请进行说明并拍照!",
                            duration: 2000,
                            position: "top"
                        });
                        tt.present();
                        return false;
                    }
                }
            }
        }

        // 判断检查结果
        if(this.resultEvaluate ==undefined || this.resultEvaluate == null){
            let tt = this.toast.create({
                message: "请对此次检查给出评价!",
                duration: 3000,
                position: "top"
            });
            tt.present();
            return false;
        }

        if(this.opinion ==undefined || this.opinion == null){
            let tt = this.toast.create({
                message: "请对此次检查给出意见!",
                duration: 3000,
                position: "top"
            });
            tt.present();
            return false;
        }

        // 保存到数据库
        console.log(this.moreElevator);
        this.httpService.querySpotCheckCacheApp({"opinion":this.opinion,"resultEvaluate":this.resultEvaluate,"implementObjectId":this.implementObjectId,"createBy":this.checkerName,"name":this.elevatorNum,"project":this.itemlist}).subscribe(data => {

            if (data != null && data.data != null) {
                let i:any=1;
                for (var key in data.data) {
                    // 封装数据
                    this.moreElevator.push({"id":i,"name":key,"createBy":this.checkerName,"project":data.data[key]})
                    console.log("属性：" + key + ",值：" + data.data[key]);
                    i++;
                }

                if (data.status != 200) {
                    let alert = this.alertCtrl.create();
                    alert.setTitle("");
                    alert.setSubTitle("此电梯已经存在检查列表中，您是否继续扫描其他电梯?");
                    alert.addButton({
                        text: "否",
                        //根据data类型 判断要跳转的页面
                        handler: () => {
                            this.navCtrl.push(CheckElevatorList,{checklist:this.moreElevator});
                        },
                    });
                    alert.addButton({
                        text: "是",
                        handler: () => {
                            this.checkItem();
                            this.elevatorIdInfo=[];
                        }
                    });
                    alert.present();

                }else{
                    console.log(this.moreElevator);

                    let alert = this.alertCtrl.create();
                    alert.setTitle("");
                    alert.setSubTitle("您是否继续扫描其他电梯?");
                    alert.addButton({
                        text: "否",
                        //根据data类型 判断要跳转的页面
                        handler: () => {
                            this.navCtrl.push(CheckElevatorList,{checklist:this.moreElevator});
                        },
                    });
                    alert.addButton({
                        text: "是",
                        handler: () => {
                            this.checkItem();
                            this.elevatorIdInfo=[];
                            this.resultEvaluate="";
                            this.opinion="";
                        }
                    });

                    alert.present();
                }
            }
        });
    }

    doCamera(index, i) {
        console.log("doCamera");
        console.log("-------------------");

        let options: CameraOptions = {
            quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
            // encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            targetWidth: 1500,
            targetHeight: 1500,
            correctOrientation: true
        };
        this.camera.getPicture(options).then(imageData => {
            //判断网络状态
            console.log("判断网络状态");
            if (!this.commonFunc.hasNetWork()) {
                if (i == 'c') {
                    console.log("c")
                    this.itemlist[index].result.picUrl.push(imageData);
                } else {
                    console.log(" ! c")
                    this.itemlist[index].result.picUrl[i] = imageData;
                }
                return;
            }
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = 'file';
            options.fileName = 'test.jpg';
            options.mimeType = 'image/jpeg';
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                let aa = JSON.parse(restul['response']);
                console.log("输出aa");
                console.log(aa);
                if (aa['status'] == 200) {
                    if (aa['data'].length > 0) {
                        if (i == 'c') {
                            console.log("c")
                            console.log(aa['data']);
                            this.itemlist[index].result.picUrl.push(aa['data']);

                        } else {
                            console.log("!c")
                            this.itemlist[index].result.picUrl[i] = aa['data'];
                        }
                    }
                }
                this.cd.detectChanges();
            });
        });
        console.log("1111111111111");
        console.log(this.itemlist);
        console.log("1111111111111");
    }

    onHold(index, param) {
        let actionSheet = this.ActionSheet.create({
            buttons: [
                {
                    text: '重拍',
                    role: '重拍',
                    handler: () => {
                        let i = this.itemlist[index].result.picUrl.indexOf(param);
                        this.doCamera(index, i);
                    }
                },
                /*{
                    text: '查看大图',
                    role: '查看大图',
                    handler: () => {
                        this.photoViewer.show(
                            encodeURI(this.whaturl(param)).replace('%5C', '/'),
                            null,
                            {
                                share: false
                            }
                        );
                    }
                },*/
                {
                    text: '删除',
                    handler: () => {
                        let i = this.itemlist[index].result.picUrl.indexOf(param);
                        this.itemlist[index].result.picUrl.splice(i, 1);
                    }
                },
                {
                    text: '取消',
                    role: '取消',
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    whaturl(url) {
        if ((url + '').indexOf('file') < 0) {
            return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
        } else {
            return url;
        }
    }

}
